<?php 
/**
 * 货品表模型
 */
class GoodsListModel extends Model{
	
	public $table = 'goods_list';
	
	//自动验证
	public $validate = array(
		array('glnumber','nonull','货品编号不能为空',2,3),
		array('glstock','regexp:/^\d{0,5}$/','请输入数字',2,3),
	);

	//组合属性验证必填
	public function nonullCombine(){
//		print_r($_POST['combinespec']);die;
		if(in_array(0, $_POST['combinespec'])){
			$this->error = '货品属性未完善';
			return false;
		}
		return true;
	}
	
	//组合属性添加验证非重
	public function addnoRepeat(){
		$gid = Q('get.gid');
		//获取组合id字段所有数据
		$data = $this->where("goods_gid={$gid}")->getField('combinespec',true);
		$combinespec = implode(',',$_POST['combinespec']);
		if(in_array($combinespec, $data)){
			$this->error = '添加的货品已存在';
			return false;
		}
		return true;
		
	}
	
	//组合属性编辑验证非重
	public function editnoRepeat(){
		$gid = Q('get.gid');
		$glid = Q('get.glid');
		//获取组合id字段所有数据
		$data = $this->where("goods_gid={$gid} AND glid NOT IN ({$glid})")->getField('combinespec',true);
		$combinespec = implode(',',$_POST['combinespec']);
		if(in_array($combinespec, $data)){
			$this->error = '添加的货品已存在';
			return false;
		}
		return true;
	}
	
	/**
	 * 添加货品
	 */
	public function addglist(){
		//执行自动验证
		if(!$this->create()) return false;
		//执行组合属性验证
		if(!$this->nonullCombine()) return false;
		//执行组合属性验证
		if(!$this->addnoRepeat()) return false;
		$data = array(
			'combinespec' => implode(',', Q('post.combinespec')),
			'glstock'	  => Q('post.glstock'),
			'glnumber' 	  => Q('post.glnumber'),
			'goods_gid'   => Q('get.gid')
		);
		$this->add($data);
		//增加商品列表中的库存
		$stockCount = $this->sum('glstock');
		//更新条件和字段值中的数据
		$upStock = array(
			'gid'  => Q('get.gid'),
			'stock'=> $stockCount,
		);
		K('Goods')->update($upStock);
		return true;
		
	}
	
	/**
	 * 编辑货品
	 */
	public function edit($glid){
		//执行自动验证
		if(!$this->create()) return false;
		//执行组合数组非空验证
		if(!$this->nonullCombine()) return false;
		//执行组合属性验证
		if(!$this->editnoRepeat()) return false;
		$data = array(
			'combinespec' => implode(',', Q('post.combinespec')),
			'glstock'	  => Q('post.glstock'),
			'glnumber'	  => Q('post.glnumber'),
			'goods_gid'	  => Q('get.gid')
		
		);
		$this->where("glid={$glid}")->update($data);
		//增加商品列表中的库存
		$stockCount = $this->sum('glstock');
		//更新条件和字段值中的数据
		$upStock = array(
			'gid'  => Q('get.gid'),
			'stock'=> $stockCount,
		);
		K('Goods')->update($upStock);
		return true;
	}
	
	
	/**
	 * 获取库存
	 */
	public function getStock($gid,$specId){
		$stock = $this->field('glstock')->where("goods_gid={$gid} AND combinespec='{$specId}'")->find();
		if($stock){
			$stock = current($stock);
		}else{
			$stock = 0;
		}
		return $stock;
	} 
	
	
	
	
}

















 ?>